class Bet < ActiveRecord::Base
  belongs_to :user,:counter_cache=>true
  belongs_to :match,:counter_cache=>true
  belongs_to :team
  belongs_to :winstreak
  validates_presence_of :user_id,:match_id,:team_id
  validates_uniqueness_of :match_id,:scope=>:user_id,:on=>:create
  named_scope :played,lambda { |played| { :conditions=>{:played=>played} }}
  named_scope :win,lambda { |win| { :conditions=>{:win=>win} }}
  named_scope :progress,lambda{{:conditions=>["#{Match.table_name}.begin_at",Time.now.to_formatted_s(:db)] }}
  named_scope :home
  named_scope :half_streak,:conditions=>{:winstreak_value=>0.5}

  named_scope :match,lambda { |m| { :conditions=>{:match_id=>m} }}

  def lost?
    !draw? && !win?
  end

  def draw?
    match.winner.nil?
  end

  alias_method :loss?,:lost?
  
  def half?
    winstreak_value == 0.5
  end

  def half_win?
    win? && half?
  end

  def half_loss?
    loss? && half?
  end

  alias_method :loss?,:lost?

  # win -> nil -> draw
  def play(match=nil)
    match = match || self.match
    # create a winsteak if not exists.
    if user.winstreak.nil?
      user.reset_winstreak
    end
    unless played?
      self.played = true
      self.win = match.winner_id.nil? ? nil : (match.winner_id == team_id) # nil is draw
      logger.debug "win: #{self.win},winner_id: #{match.winner_id},team_id #{team_id}"
      self.winstreak = user.winstreak
      self.winstreak_value = match.winstreak_value
      save!

      winstreak = self.winstreak
      winstreak.streak_count = winstreak.streak_count.to_f + winstreak_value.to_f
      winstreak.save!

      # process winstreak
      if lost? # lose
        # reset user winstreak
        if half_loss?
          if winstreak.half_loss_full?
            user.reset_winstreak
          end
        else
          user.reset_winstreak
        end
      end


      user.calc_percentage unless win.nil?
      user.winstreak.calc
    end
  end

  def validate_on_create
    errors.add :match_id,"has already been played." if match.played?
    errors.add :match_id,"expired." if Time.now > match.begin_at 
  end
end
